package com.buercorp.yiyu.jdbc;

import java.sql.*;
import java.util.*;

public class JdbcDemo01 {
    public static void main(String[] args) throws Exception {
        // 注册驱动
        Class.forName("com.mysql.jdbc.Driver");

        // 获取连接
        String url = "jdbc:mysql://127.0.0.1:3306/db1";
        String username = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, username, password);

        // 定义sql
        String sql = "insert into user(username, password, age) values(?, ?, ?)";

        // 获取执行sql的对象 statement
        // Statement stmt = connection.createStatement();

        PreparedStatement state = connection.prepareStatement(sql);
//        state.setInt(1, 1);
        state.setString(1, "test");
        state.setString(2, "123456");
        state.setInt(3, 18);

        // insert update select delete
        // insert into 表名（包含的字段）values(?,?,?...)
        // delete from 表名 where 字段 = ?
        // update 表名 set 字段 = ? (可以多个) where 字段 = ?
        // select (需要查询的字段) from 表名 where 字段 = ？

        // 执行sql
//        boolean count = state.execute();
        int row = state.executeUpdate();

        if (row > 0) {
            System.out.println("插入成功！");
        }



        String selectSQL = "select * from user";
        PreparedStatement state1 = connection.prepareStatement(selectSQL);
        ResultSet rs = state1.executeQuery();
        List<User> list = new ArrayList<>();
        while (rs.next()) {
            User user = new User(rs.getInt("id"), rs.getString("username"), rs.getString("password"), rs.getInt("age"));
            list.add(user);
        }
        list.forEach(System.out::println);
        System.out.println("row = " + row);

        // 处理结果
//        System.out.println(count);

        // 释放资源
        state.close();
        connection.close();
    }
}
